import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        productList: [{
                name: 'goods 1',
                price: 100
            },
            {
                name: 'goods 2',
                price: 200
            },
            {
                name: 'goods 3',
                price: 300
            },
            {
                name: 'goods 3',
                price: 400
            }
        ]
    },
    // getters用于从state中派生出一些状态，例如对列表进行过滤等。可以将getters理解为计算属性computed，getter的返回值会根据它的依赖被缓存起来，且只有当它的依赖值发生了改变才会被重新计算
    getters: {
        getSaledPrice: (state) => {
            let saleProduct = state.productList.map((item) => {
                return {
                    name: item.name + '/2',
                    price: item.price / 2
                }
            })
            return saleProduct
        }
    },
    mutations: {
        reducePrice: (state, payload) => {
            return state.productList.forEach((product) => {
                product.price -= payload;
            })
        }
    },
    // 提交的是mutation，可以包含异步操作
    actions: {
        reducePriceAsync: (context, payload) => {
            setTimeout(() => {
                context.commit('reducePrice', payload); // reducePrice为上一步mutation中的属性
            }, 2000)
        }
    }
});